﻿using System;
using System.Text;
using System.Data;

namespace SlamCms.Data.Repositories
{
	public class ContentItemRepository : IContentItemRepository
	{
		private readonly IDbConnection _connection;

		public ContentItemRepository(IDbConnection connection)
		{
			_connection = connection;
		}

		public void SaveTags(ContentItem item)
		{
			var sb = new StringBuilder();
			sb.AppendLine("begin");
			sb.AppendFormat("DELETE FROM [ContentItemTag] WHERE ContentItemID = '{0}' ", item.ContentItemId);
			foreach (var tag in item.Tags)
			{	
				sb.AppendFormat(@"	begin 
												if not exists(select 1 from ContentItemTag where ContentItemID = '{0}' and TagID = '{1}')
													INSERT INTO [ContentItemTag] ([ContentItemID],[TagID]) VALUES ('{0}', '{1}') 
											end ", item.ContentItemId, tag.TagId);
			}
			sb.AppendLine("end");
			_connection.Execute(sb.ToString(), "");
		}

		public void UpdateExpirationDate(string contentItemId, DateTime? expirationDate, int userId)
		{
			var sql = @"UPDATE [ContentItem] SET ExpirationDate = @ExpirationDate, VerifiedDate = GETDATE(), VerifiedByUserId = @UserId WHERE ContentItemId = @ContentItemId";
			_connection.Execute(sql, new { ExpirationDate = expirationDate, UserId = userId, ContentItemId = contentItemId });
		}
	}
}
